package com.sand.pro.flinksql_pro.time.eventtime;

import com.sand.pro.flinksql_pro.bean.WaterSensor;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

import java.time.Duration;

import static org.apache.flink.table.api.Expressions.$;

public class TableEventTime {
    public static void main(String[] args) {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        SingleOutputStreamOperator<WaterSensor> waterSensorStream = env
                .fromElements(new WaterSensor("sensor_1" , System.currentTimeMillis() + 1000L, 10),
                        new WaterSensor("sensor_1" , System.currentTimeMillis() + 2000L, 20),
                        new WaterSensor("sensor_2" , System.currentTimeMillis() + 3000L, 30),
                        new WaterSensor("sensor_1" , System.currentTimeMillis() + 4000L, 40),
                        new WaterSensor("sensor_1" , System.currentTimeMillis() + 5000L, 50),
                        new WaterSensor("sensor_2" , System.currentTimeMillis() + 6000L, 60))
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(5))
                                .withTimestampAssigner((element, recordTimestamp) -> element.getTs())
                );

        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);
        Table table = tableEnv
                // 用一个额外的字段作为事件时间属性
//                .fromDataStream(waterSensorStream, $("id"), $("ts"), $("vc"), $("et").rowtime());
                // 使用已有的字段作为时间属性
                .fromDataStream(waterSensorStream, $("id"), $("ts").rowtime(), $("vc"));

        table.execute().print();
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
